from flask import current_app, abort, render_template, g, jsonify, request

from info import db
from info.constants import HOME_PAGE_MAX_NEWS
from info.models import News, Comment, User
from info.modules.news import news_blu
from info.utils.common import user_login_data

# 2.使用蓝图对象来注册路由
from info.utils.response_code import RET, error_map


@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    user = g.user
    # 根据id进行模板渲染
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return abort(500)

    news_list = []

    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(HOME_PAGE_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)

    # 判断新闻是否被该用户收藏
    is_collection = False
    if user:
        if news in user.collection_news:
            is_collection = True

    # 　判断新闻是否被用户关注
    is_followed = False
    if user and news.user:
        if news.user in user.followed:
            is_followed = True

    # 查询该新闻的所有评论
    comments = news.comments.order_by(Comment.create_time.desc()).all()
    comment_list = []
    # 查询哪些评论被点赞
    for comment in comments:
        is_like = False
        comment_dict = comment.to_dict()

        if user:
            if comment in user.like_comments:
                is_like = True

        comment_dict["is_like"] = is_like
        comment_list.append(comment_dict)

    news_list = [news.to_dict() for news in news_list]

    user = g.user.to_dict() if g.user else None
    # 增加点击量
    news.clicks += 1

    # 传入模板渲染
    return render_template("news/detail.html", news=news.to_dict(), user=user, news_list=news_list,
                           is_collection=is_collection, comment_list=comment_list, is_followed=is_followed)


# 新闻收藏
@news_blu.route("/news_collect", methods=["POST"])
@user_login_data
def news_collect():
    # 判断用户是否登录:
    user = g.user
    if not user:  # 未登录
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    # 获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.INPARAERR, errmsg=error_map[RET.INPARAERR])

    try:
        news_id = int(news_id)
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 查询新闻数据
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 根据action建立/接触收藏关系(使用关系属性进行关联)
    if action == "collect":
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    # json返回结果
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


@news_blu.route("/news_comment", methods=["POST"])
@user_login_data
def news_comment():
    user = g.user
    if not user:
        return abort(403)

    # 获取参数
    news_id = request.json.get("news_id")
    comment_content = request.json.get("comment")
    parent_id = request.json.get("parent_id")

    # 校验参数
    if not all([news_id, comment_content]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 生成评论记录
    comment = Comment()
    comment.content = comment_content
    comment.user_id = user.id
    comment.news_id = news_id
    # 如果有父评论
    if parent_id:
        try:
            parent_id = int(parent_id)
            comment.parent_id = parent_id
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    # 添加到会话当中
    db.session.add(comment)

    # 手动提交, 为了comment_id
    try:
        db.session.commit()
    except BaseException as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 返回json
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=comment.to_dict())


@news_blu.route("/comment_like", methods=["POST"])
@user_login_data
def comment_like():
    # 判断用户是否登陆
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])
    # 获取参数
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")

    # 校验参数
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        comment_id = int(comment_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 查询评论数据
    try:
        comment = Comment.query.get(comment_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 根据action的值判断关系
    if action == "add":
        user.like_comments.append(comment)
        comment.like_count += 1
    else:
        user.like_comments.remove(comment)
        comment.like_count -= 1

    # 返回json
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 关注/取消关注
@news_blu.route("/followed_user", methods=["POST"])
@user_login_data
def followed_user():
    user = g.user
    if not user:
        return abort(403)

    # 获取和校验参数
    author_id = request.json.get("user_id")
    action = request.json.get("action")
    try:
        author_id = int(author_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action not in ["follow", "unfollow"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 查询作者数据
    try:
        author = User.query.get(author_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 　根据action判断行为
    if action == "follow":
        user.followed.append(author)
    else:
        user.followed.remove(author)
    # 　返回json
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])
